//
//  CartViewController.m
//  ZPSALE
//
//  Created by tmosport on 14-4-16.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "CartViewController.h"
#import "cartTableViewCell.h"
#import "creatOrderViewController.h"
#import "logOnViewController.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"

@interface CartViewController ()
@property (nonatomic) BOOL isLogin;
@property (nonatomic) BOOL allCheckStatus;
@property (nonatomic,retain) NSArray *cartListArr;
@property (nonatomic,copy)NSString *memberId;
@property (nonatomic,copy)NSString *aliasid;
@property (nonatomic,copy)NSString *atoken;
@property (nonatomic)NSInteger needpay;
@property (nonatomic,strong) UIView *baseHeader;
- (IBAction)selectGood:(UIButton *)sender;
@property (strong, nonatomic) IBOutlet UIButton *goBuyBT;
- (IBAction)goBuyAction:(UIButton *)sender;
@property (strong, nonatomic) IBOutlet UIView *noGoodsView;
@property (strong, nonatomic) IBOutlet UIView *subView;
- (IBAction)allSelect:(UIButton *)sender;
@property(nonatomic,strong)NSString *allChecked;
- (IBAction)creatOrder:(UIButton *)sender;

- (IBAction)comCart:(UIButton *)sender;

@end

@implementation CartViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)awakeFromNib {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationForNumberOfCart:) name:@"changeNumberOfProductInCart" object:nil];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationForCombineCart:) name:@"combineCart" object:nil];
}

-(void)viewWillAppear:(BOOL)animated {
    //checkLogin
    [[NSNotificationCenter defaultCenter] postNotificationName:StringForCheckLogin object:nil];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNavigationItem];
    [self setupTableView];//
    self.title = @"购物车";
    [self setupItem];
    _allCheckStatus = YES;
}

-(void)setNavigationItem {
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)notificationForNumberOfCart:(NSNotification *)notification {
    [self getNumberOfProductInCart];
}
//-(void)notificationForCombineCart:(NSNotification *)notification {
//    [self combineCart];
//}
-(void)getNumberOfProductInCart {
    NSDictionary *paraDict;
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    NSString *memeberId = [dataDic valueForKey:@"memberId"];
    //判断是游客还是用户
    if ([memeberId length] == 0 ||[memeberId isEqual:[NSNull null]]) {
        
    } else {
        paraDict = @{
                     @"memberid":memeberId
                     };
        AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
        
        [httpManager GET:APIURL"sale/getCartNum.json" parameters:paraDict success:^(AFHTTPRequestOperation *operation ,id resultObject){
            int numOfProduct = [resultObject[@"cartnum"] intValue];
            if (numOfProduct == 0) {
                self.navigationController.tabBarItem.badgeValue = nil;
            } else {
                self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",numOfProduct];
            }
        } failure:^(AFHTTPRequestOperation *operation,NSError *error) {
            //DO:错误捕获
        }];

    }
    
}

-(void)combineCart {
    //合并购物车
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    NSString *memeberId = [dataDic valueForKey:@"memberId"];
    NSString *aliasid = [dataDic valueForKey:@"aliasid"];
    if ([memeberId length] == 0 ||[memeberId isEqual:[NSNull null]] || [aliasid length] == 0 ||[aliasid isEqual:[NSNull null]]) {
        return;
     }
      NSDictionary *paraDict = @{
                     @"memberid":memeberId,
                     @"aliasid":aliasid
                     };

    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    [httpManager GET:APIURL"cart/combineMem.json" parameters:paraDict success:^(AFHTTPRequestOperation *operation ,id resultObject){
        [self getNumberOfProductInCart];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error) {
        //Do:错误捕获
    }];
}


- (void)setupItem
{
   
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 12, 40, 30);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button setTitleColor:ColorFromRGB(0x666666) forState:UIControlStateNormal];
    [button setTitleColor:ColorFromRGB(0x666666) forState:UIControlStateSelected];
    [button setBackgroundColor:[UIColor whiteColor]];
    [button setTitle:@"编辑" forState:UIControlStateNormal];
    [button setTitle:@"完成" forState:UIControlStateSelected];
    [button setTitleEdgeInsets:UIEdgeInsetsMake(2, 0, 0, 0)];
    [button addTarget:self action:@selector(toEdit:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc]
                                initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = barItem;
    
    [_checkOutBT.layer setCornerRadius:4.0];
    [_checkOutBT setBackgroundColor:ColorFromRGB(0xff0100)];
    [_goBuyBT.layer setCornerRadius:4.0];
    [_goBuyBT setBackgroundColor:ColorFromRGB(0xff0100)];
    
}
- (void)setupTableView
{
    //去tableview——footer
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    self.cartTV.tableFooterView = view;
}

- (void)viewDidAppear:(BOOL)animated
{
    [self dataInit];
}

-(void)toEdit:(UIButton *)button
{
    if (self.cartTV.editing == YES) {
        [self.cartTV setEditing:NO animated:YES];
        button.selected = NO;
        self.navigationItem.rightBarButtonItem.title = @"编辑";
    }else{
    
        [self.cartTV setEditing:YES animated:YES];
        button.selected = YES;
        self.navigationItem.rightBarButtonItem.title = @"完成";
    }
    [self.cartTV reloadData];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"createOrder"]) {
        creatOrderViewController *destVC = segue.destinationViewController;
        destVC.memberId = _memberId;
        destVC.atoken = _atoken;
        destVC.hidesBottomBarWhenPushed = YES;
    }else{
       
    }
}

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    BOOL loginStatus;
    if (_isLogin) {
        loginStatus =  YES;
    }else{
        [self login];
        loginStatus =  NO;
    }
    return loginStatus;
}

- (void)login{
    logOnViewController *loginVC = (logOnViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"logOnViewController"];
    UINavigationController *navigationVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    
    navigationVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    navigationVC.navigationBar.tintColor = [UIColor blackColor];
    // present
    [self presentViewController:navigationVC animated:YES completion:nil];
}

- (void)dataInit{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.dimBackground = NO;
    
    
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    _memberId = [dataDic valueForKey:@"memberId"];
    _atoken = [dataDic valueForKey:@"token"];
    _aliasid = [dataDic valueForKey:@"aliasid"];
    NSDictionary *params;
    if ([_memberId length] == 0 ||[_memberId isEqual:[NSNull null]] ||[_atoken isEqual:[NSNull null]] ||[_atoken length] == 0) {
        _isLogin = NO; //默认标记
       
    }else{
        _isLogin = YES;
        params = @{@"memberid": _memberId};
        AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
        [manger GET:APIURL@"sale/getCartList.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *orderListsDic = (NSDictionary *)responseObject;
            self.cartListArr = orderListsDic[@"productsInCart"];
            //        if (_isLogin == YES) {
            //            UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
            //            self.cartTV.tableHeaderView = view;
            //        }
            if ([self.cartListArr count] == 0) {
                self.cartTV.tableFooterView = _noGoodsView;
                _totalMount.text = @" ";
                _needpay = 0;
            }else{
                _totalMount.text = [NSString stringWithFormat:@"%@",orderListsDic[@"price"]];
                _needpay =[orderListsDic[@"price"] integerValue];
                //全选遍历所有
                NSInteger count = [self.cartListArr count];
                _allCheckStatus = true;
                for (NSUInteger i = 0; i < count; i++) {
                    NSArray *itemsArr = [self.cartListArr objectAtIndex:i][@"items"];
                    NSInteger jcount = [itemsArr count];
                    for (NSUInteger j = 0; j < jcount; j++) {
                        NSDictionary *sectionDic = [itemsArr objectAtIndex:j];
                        NSInteger statusInt =[sectionDic[@"checked"] intValue];
                        if(_allCheckStatus && (statusInt >0) ){
                            _allCheckStatus = true;
                            _allCheckBt.selected = YES;
                        }else{
                            _allCheckBt.selected = NO;
                            _allCheckStatus = false;
                        }
                    }
                }
                //全选逻辑
            }
            [self.cartTV reloadData];
            [HUD hide:YES];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [HUD hide:YES afterDelay:1];
        }];

    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - tableView-dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectZero];

    if ([_cartListArr count] == 0) {
        self.subView.hidden = YES;
    }else{
        self.cartTV.tableFooterView = view;
        self.subView.hidden = NO;
    }
    return [_cartListArr count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *cartSection = [_cartListArr objectAtIndex:section];
    NSArray *sectionArr = cartSection[@"items"];
    return [sectionArr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cartTableViewCell *cell;
    if (tableView.editing == YES) {
        cell = nil;
        cell = (cartTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"editCell"];

        UILabel *brandName = (UILabel *)[cell.contentView viewWithTag:102];
        UILabel *productName = (UILabel *)[cell.contentView viewWithTag:103];

        UILabel *price = (UILabel *)[cell.contentView viewWithTag:105];
        NSArray *sectionArr = [_cartListArr objectAtIndex:indexPath.section][@"items"];
        NSDictionary *sectionDic = [sectionArr objectAtIndex:indexPath.row];
//        UIView *changNumView = (UIView *)[cell viewWithTag:99];
        UIImageView *pImgView = (UIImageView *)[cell.contentView viewWithTag:101];
        [pImgView sd_setImageWithURL:Return_imageUrl(sectionDic[@"imageSource"], 180) placeholderImage:[UIImage imageNamed:@"noimage"] options:SDWebImageRetryFailed];
        
        UIButton *plusBt = (UIButton *)[cell.contentView viewWithTag:110];
        plusBt.backgroundColor = ColorFromRGB(0xd7d7d7);
        plusBt.tag =[sectionDic[@"productspecid"] intValue];
        [plusBt addTarget:self action:@selector(changNumPlus:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *minBT = (UIButton *)[cell.contentView viewWithTag:111];
        minBT.backgroundColor = ColorFromRGB(0xd7d7d7);
        minBT.tag =[sectionDic[@"productspecid"] intValue];
        [minBT addTarget:self action:@selector(changNumMin:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *changNum = (UILabel *)[cell.contentView viewWithTag:112];
        changNum.text = [NSString stringWithFormat:@"%@",[sectionDic valueForKey:@"num"]];
        NSString *brandname = [NSString stringWithFormat:@"%@",[sectionDic valueForKey:@"brandname"]];
        brandName.text =[NSString stringWithFormat:@"%@",brandname]; //_orderListsDic[@"cardType"];
        productName.textColor = RGB(51, 51, 51);
        productName.text = [NSString stringWithFormat:@"%@",[sectionDic valueForKey:@"productname"]];
        
        price.text = [NSString stringWithFormat:@"￥ %@",[sectionDic valueForKey:@"price"]];
    }else{
        cell = nil;
        cell = (cartTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"normalCell"];
        UILabel *brandName = (UILabel *)[cell.contentView viewWithTag:102];
        UILabel *productName = (UILabel *)[cell.contentView viewWithTag:103];
        UILabel *extInfo = (UILabel *)[cell.contentView viewWithTag:104];
        UILabel *price = (UILabel *)[cell.contentView viewWithTag:105];
        NSArray *sectionArr = [_cartListArr objectAtIndex:indexPath.section][@"items"];
        NSDictionary *sectionDic = [sectionArr objectAtIndex:indexPath.row];
        UIImageView *pImgView = (UIImageView *)[cell.contentView viewWithTag:101];
        [pImgView sd_setImageWithURL:Return_imageUrl(sectionDic[@"imageSource"], 180) placeholderImage:[UIImage imageNamed:@"noimage"] options:SDWebImageRetryFailed];
        NSInteger statusInt =[sectionDic[@"checked"] intValue];
        
        cell.checkButton.selected = statusInt > 0  ? YES : NO;
        cell.checkButton.tag = [sectionDic[@"productspecid"] intValue];
        NSString *brandname = [NSString stringWithFormat:@"%@",[sectionDic valueForKey:@"brandname"]];
        brandName.text =[NSString stringWithFormat:@"%@",brandname]; //_orderListsDic[@"cardType"];
        productName.textColor = RGB(51, 51, 51);
        productName.text = [NSString stringWithFormat:@"%@",[sectionDic valueForKey:@"productname"]];
        extInfo.text = [NSString stringWithFormat:@"X%@",[sectionDic valueForKey:@"num"]];
        price.text = [NSString stringWithFormat:@"￥ %@",[sectionDic valueForKey:@"price"]];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    //section头，用来展示活动类型
    UIView *sectionHeadView = [UIView new];
    CGRect headFrame;
    headFrame = CGRectMake(0, 0, 320, 10);
    sectionHeadView.frame = headFrame;
    [sectionHeadView setBackgroundColor:ColorFromRGB(0xf6f6f6)];
    return sectionHeadView;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCellEditingStyle  result = UITableViewCellEditingStyleNone;
    
    if (tableView.editing) {
        result = UITableViewCellEditingStyleNone;
    }else{
        result = UITableViewCellEditingStyleDelete;
    }
   
    return result;
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}


- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL canMove;
    if (tableView.editing) {
        canMove = NO;
    }else{
        canMove = YES;
    }
    return canMove;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *sectionArr = [_cartListArr objectAtIndex:indexPath.section][@"items"];
    NSDictionary *sectionDic = [sectionArr objectAtIndex:indexPath.row];
    NSString *dropId = sectionDic[@"productspecid"];
    NSDictionary *params;
    if ([_memberId length] == 0 ||[_memberId isEqual:[NSNull null]] ||[_atoken isEqual:[NSNull null]] ||[_atoken length] == 0) {
        _isLogin = NO; //默认标记
        
    }else{
        _isLogin = YES;
        params = @{@"memberid": _memberId,
                   @"productspecid": dropId,
                   };
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.dimBackground = NO;
        
        AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
        [manger POST:APIURL@"sale/dropItem.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *orderListsDic = (NSDictionary *)responseObject;
            self.cartListArr = orderListsDic[@"productsInCart"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeNumberOfProductInCart" object:nil];
            [self.cartTV reloadData];
            [HUD hide:YES];
            if ([self.cartListArr count] == 0) {
                self.cartTV.tableFooterView = _noGoodsView;
                _totalMount.text = @" ";
                _needpay = 0;
            }else{
                _totalMount.text = [NSString stringWithFormat:@"%@",orderListsDic[@"price"]];
                _needpay = [orderListsDic[@"price"] integerValue];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [HUD hide:YES];
            //DO:错误捕获
        }];
    }
    
}

- (void)changNumPlus:(UIButton *)sender {
    //商品数量增加
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.cartTV];
    NSIndexPath *ip = [self.cartTV indexPathForRowAtPoint:buttonPosition];//获取按钮所在cellIP
    NSArray *sectionArr = [_cartListArr objectAtIndex:ip.section][@"items"];
    NSDictionary *sectionDic = [sectionArr objectAtIndex:ip.row];
    NSInteger currentNum =[sectionDic[@"num"] intValue];
    NSString *quantity ;
    if ((currentNum + 1) >3) {
        return;
    }else{
        quantity = [NSString stringWithFormat:@"%d",currentNum +1];
    }
    NSString *specId = [NSString stringWithFormat:@"%d",[sectionDic[@"productspecid"] intValue]];
    NSDictionary *params;
    if ([_memberId length] == 0 ||[_memberId isEqual:[NSNull null]] ||[_atoken isEqual:[NSNull null]] ||[_atoken length] == 0) {
        _isLogin = NO; //默认标记
        
    }else{
        _isLogin = YES;
        params = @{@"memberid": _memberId,
                   @"productspecid": specId,
                   @"quantity": quantity
                   };
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.dimBackground = NO;
        
        AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
        [manger POST:APIURL@"sale/updateProduct.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *orderListsDic = (NSDictionary *)responseObject;
            if ([orderListsDic[@"error"] length]>0) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:orderListsDic[@"error"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                [HUD hide:YES];
                return;
            }else{
                self.cartListArr = orderListsDic[@"productsInCart"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"changeNumberOfProductInCart" object:nil];
                [self.cartTV reloadData];
                [HUD hide:YES];
                if ([self.cartListArr count] == 0) {
                    self.cartTV.tableFooterView = _noGoodsView;
                    _totalMount.text = @" ";
                    _needpay = 0;
                }else{
                    _totalMount.text = [NSString stringWithFormat:@"%@",orderListsDic[@"price"]];
                    _needpay = [orderListsDic[@"price"] integerValue];
                }
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [HUD hide:YES];
            //DO:错误捕获
        }];
    }
    
    
    
}
- (void)changNumMin:(UIButton *)sender {
    //商品数量减少
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.cartTV];
    NSIndexPath *ip = [self.cartTV indexPathForRowAtPoint:buttonPosition];

    NSArray *sectionArr = [_cartListArr objectAtIndex:ip.section][@"items"];
    NSDictionary *sectionDic = [sectionArr objectAtIndex:ip.row];
    NSInteger currentNum =[sectionDic[@"num"] intValue];
    NSString *quantity ;
    if ((currentNum - 1) <= 0) {
        return;
    }else{
        quantity = [NSString stringWithFormat:@"%d",currentNum -1];
    }
    NSString *specId = [NSString stringWithFormat:@"%d",[sectionDic[@"productspecid"] intValue]];
    NSDictionary *params;
    
    if ([_memberId length] == 0 ||[_memberId isEqual:[NSNull null]] ||[_atoken isEqual:[NSNull null]] ||[_atoken length] == 0) {
        _isLogin = NO; //默认标记
       
    }else{
        _isLogin = YES;
        params = @{@"memberid": _memberId,
                   @"productspecid": specId,
                   @"quantity": quantity
                   };
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.dimBackground = NO;
        
        AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
        [manger POST:APIURL@"sale/updateProduct.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *orderListsDic = (NSDictionary *)responseObject;
            if ([orderListsDic[@"error"] length]>0) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:orderListsDic[@"error"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                [HUD hide:YES];
                return;
            }else{
                self.cartListArr = orderListsDic[@"productsInCart"];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"changeNumberOfProductInCart" object:nil];
                [self.cartTV reloadData];
                [HUD hide:YES];
                if ([self.cartListArr count] == 0) {
                    self.cartTV.tableFooterView = _noGoodsView;
                    _totalMount.text = @" ";
                    _needpay = 0;
                }else{
                    _totalMount.text = [NSString stringWithFormat:@"%@",orderListsDic[@"price"]];
                    _needpay = [orderListsDic[@"price"] integerValue];
                }
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [HUD hide:YES];
            //DO:错误捕获
        }];

    }
}


- (IBAction)selectGood:(UIButton *)sender {
    //更新商品选中状态，多款商品有可能需修复
    sender.selected =! sender.selected;
    NSString *specId = [NSString stringWithFormat:@"%d",sender.tag];
    NSDictionary *params;
    if ([_memberId length] == 0 ||[_memberId isEqual:[NSNull null]] ||[_atoken isEqual:[NSNull null]] ||[_atoken length] == 0) {
        _isLogin = NO; //默认标记
    }else{
        _isLogin = YES;
        params = @{@"memberid": _memberId,
                   @"specid": specId                   };
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.dimBackground = NO;
        
        AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
        [manger POST:APIURL@"sale/updateCheck.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *orderListsDic = (NSDictionary *)responseObject;
            self.cartListArr = orderListsDic[@"productsInCart"];
            if ([self.cartListArr count] == 0) {
                self.cartTV.tableFooterView = _noGoodsView;
                _totalMount.text = @" ";
                _needpay = 0;
            }else{
                _totalMount.text = [NSString stringWithFormat:@"%@",orderListsDic[@"price"]];
                _needpay = [orderListsDic[@"price"] integerValue];
                //全选遍历所有
                NSInteger count = [self.cartListArr count];
                _allCheckStatus = true;
                for (NSUInteger i = 0; i < count; i++) {
                    NSArray *itemsArr = [self.cartListArr objectAtIndex:i][@"items"];
                    NSInteger jcount = [itemsArr count];
                    for (NSUInteger j = 0; j < jcount; j++) {
                        NSDictionary *sectionDic = [itemsArr objectAtIndex:j];
                        NSInteger statusInt =[sectionDic[@"checked"] intValue];
                        if(_allCheckStatus && (statusInt >0) ){
                            _allCheckStatus = true;
                            _allCheckBt.selected = YES;
                        }else{
                            _allCheckBt.selected = NO;
                            _allCheckStatus = false;
                        }
                    }
                }
                //全选逻辑
            }
            [self.cartTV reloadData];
            [HUD hide:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //DO:错误捕获
            [HUD hide:YES];
        }];
    }
    
}

- (IBAction)allSelect:(UIButton *)sender {
    sender.selected =! sender.selected;
    _allChecked = sender.selected ? @"1" : @"0";

    NSDictionary *params;
    if ([_memberId length] == 0 ||[_memberId isEqual:[NSNull null]] ||[_atoken isEqual:[NSNull null]] ||[_atoken length] == 0) {
        _isLogin = NO; //默认标记

    }else{
        _isLogin = YES;
        params = @{@"memberid": _memberId,
                   @"checked": _allChecked
                   };
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        HUD.dimBackground = NO;
        
        AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
        [manger POST:APIURL@"sale/updateCheckAllCart.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *orderListsDic = (NSDictionary *)responseObject;
            self.cartListArr = orderListsDic[@"productsInCart"];
            if ([self.cartListArr count] == 0) {
                self.cartTV.tableFooterView = _noGoodsView;
                _totalMount.text = @" ";
                _needpay = 0;
            }else{
                _totalMount.text = [NSString stringWithFormat:@"%@",orderListsDic[@"price"]];
                _needpay =[orderListsDic[@"price"] integerValue];
            }
            
            [self.cartTV reloadData];
            [HUD hide:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //DO:错误捕获
            [HUD hide:YES];
        }];

    }
   
}
- (IBAction)creatOrder:(UIButton *)sender {

    if (!_isLogin) {
        [self login];
        return;
    }
    if (_needpay >0) {
        creatOrderViewController *createVc = [self.storyboard instantiateViewControllerWithIdentifier:@"creatOrderViewController"];
        createVc.hidesBottomBarWhenPushed = YES;
        createVc.memberId = _memberId;
        createVc.atoken = _atoken;
        [self.navigationController pushViewController:createVc animated:YES];
    }else{
        UIAlertView *tips = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请至少选择购买一件商品" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [tips show];
        return;
    }
}


- (IBAction)goBuyAction:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (IBAction)comCart:(UIButton *)sender {
    [self login];
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeNumberOfProductInCart" object:nil];
}
//- (void)viewDidDisappear:(BOOL)animated
//{//移除Ob
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeNumberOfProductInCart" object:Nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"combineCart" object:Nil];
//}

@end
